import React, {useEffect, useState} from 'react';
import { IndexBar, List } from 'antd-mobile'
// @ts-ignore
import {connect} from 'dva'

function City(props:any) {
  const [cityList,setcityList] = useState<any>([])

  // 经过数据处理函数，得到26字母的二级数组
  const filterCity = (cities:any) => {
    const letterArr: Array<string> = []
    const newList = []
    for (let i=65;i<91;i++){
      letterArr.push(String.fromCharCode(i))
    }
    for (let m in letterArr){
      const letterCityList = cities.filter((item:any) =>item.pinyin.substring(0,1).toUpperCase() === letterArr[m])
      letterCityList.length && newList.push({
        letter: letterArr[m],
        cities: letterCityList
      })
    }
    // console.log(newList)

    return newList
  }

  useEffect(() => {
    fetch("https://m.maizuo.com/gateway?k=5115595", {
      headers: {
        'X-Client-Info': '{"a":"3000","ch":"1002","v":"5.2.0","e":"1640782700594797135921153"}',
        'X-Host': 'mall.film-ticket.city.list'
      }
    }).then(res=>res.json())
      .then(res => {
        // console.log(res.data.cities)

        // 传入数据处理函数
        // filterCity(res.data.cities)


        setcityList(filterCity(res.data.cities))
        // console.log(cityList)
      })
  }, [])

  const handleChangeCity = (item:any) => {
    // console.log(item)

    // 将 cityName 和 Id 传到公共状态
    props.dispatch({
      type:'city/changeCity',
      payload: {
        cityName: item.name,
        cityId: item.cityId
      }
    })

    props.history.push('/cinemas')
  }

  return (
    <div style={{ height: window.innerHeight }}>
      <IndexBar>
        {cityList.map((item:any) => {
          const { letter, cities } = item
          return (
            <IndexBar.Panel
              index={letter}
              title={letter}
              key={letter}
            >
              <List>
                {cities.map((item:any, index:number) => (
                  <List.Item key={index} onClick={() => handleChangeCity(item)}>{item.name}</List.Item>
                ))}
              </List>
            </IndexBar.Panel>
          )
        })}
      </IndexBar>
    </div>
  )
}
// ({}): 表示返回一个空对象
export default connect(() => ({}))(City)
